﻿using SD.Business;
using SD.DataAccess;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using SD.Commons;
using System.Web.UI.MobileControls;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Globalization;

namespace SD.Web.Views.TeamMaintenance
{
    public partial class TeamList : System.Web.UI.Page
    {
        HiddenField hiddentFielId;
        /// <summary>
        /// Maintain the filter value
        /// </summary>
        public Collection<string> Filter
        {
            get
            {
                if (ViewState["Filter"] != null)
                {
                    return (Collection<string>)this.ViewState["Filter"];
                }
                else
                {
                    return null;
                }
            }

            set
            {
                this.ViewState["Filter"] = value;
            }
        }

        /// <summary>
        /// Maintain the sort value
        /// </summary>
        public string SortType
        {
            get
            {
                if (ViewState["sortType"] != null)
                {
                    return this.ViewState["sortType"].ToString();
                }
                else
                {
                    this.ViewState["sortType"] = "TeamName";
                    return this.ViewState["sortType"].ToString();
                }
            }

            set
            {
                this.ViewState["sortType"] = value;
            }
        }

        /// <summary>
        /// Maintain the total pages of datagrid
        /// </summary>
        public int PageCount
        {
            get
            {
                return Convert.ToInt16(this.ViewState["PageCount"].ToString());
            }

            set
            {
                this.ViewState["PageCount"] = value;
            }
        }

        /// <summary>
        /// Check the status of sort and filter
        /// </summary>
        public int[] Flag
        {
            get
            {
                if (ViewState["Flag"] != null)
                {
                    return (int[])this.ViewState["Flag"];
                }
                else
                {
                    int[] flag = new int[2];
                    flag[0] = 0;
                    flag[1] = 0;
                    this.ViewState["Flag"] = flag;
                    return (int[])this.ViewState["Flag"];
                }
            }

            set
            {
                this.ViewState["Flag"] = value;
            }
        }

        /// <summary>
        /// Maintain the current page
        /// </summary>
        public int CurPage
        {
            get
            {
                if (this.ViewState["CurrentPage"] == null)
                    return 1;
                else
                    return Convert.ToInt16(this.ViewState["CurrentPage"].ToString());
            }

            set
            {
                this.ViewState["CurrentPage"] = value;
            }
        }


        /// <summary>
        /// Fill the data to the form
        /// </summary>
        /// <param name="filter">type of filter</param>
        /// <param name="sortType">type of sort</param>
        public void LoadData(Collection<string> filter, string sortType)
        {
            int department;
            if (Request.Params["departmentId"] != null)
            {
                if (int.TryParse(Request.Params["departmentId"], out department))
                {
                    List<Team> teams = new List<Team>();

                    //sort type team name
                    if (sortType == "TeamName")
                    {
                        if (Flag[0] % 2 == 0)
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderBy(item => item.TeamName).ToList();
                        else
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderByDescending(item => item.TeamName).ToList();
                    }

                    //sort type AddressId
                    if (sortType == "AddressLine")
                    {
                        if (Flag[0] % 2 == 0)
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderBy(item => item.Address.AddressLine).ToList();
                        else
                            teams = TeamBus.ListTeam(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.Address.AddressLine).ToList();
                    }
                    //sort type contact name
                    if (sortType == "Postcode")
                    {
                        if (Flag[0] % 2 == 0)
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderBy(item => item.Address.Postcode).ToList();
                        else
                            teams = TeamBus.ListTeam(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.Address.Postcode).ToList();
                    }

                    //sort type postcode
                    if (sortType == "KnownAs")
                    {
                        if (Flag[0] % 2 == 0)
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderBy(item => item.Contact.KnownAs).ToList();
                        else
                            teams = TeamBus.ListTeam(CheckBoxInactive.Checked, filter).OrderByDescending(item => item.Contact.KnownAs).ToList();
                    }
                    //sort type isactive
                    if (sortType == "IsActive")
                    {
                        if (Flag[0] % 2 == 0)
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderBy(item => item.IsActive).ToList();
                        else
                            teams = TeamBus.ListTeamByDepartment(CheckBoxInactive.Checked, filter, department).OrderByDescending(item => item.IsActive).ToList();
                    }



                    //total page
                    PageCount = (int)Math.Ceiling(teams.Count / 10.0);
                    if (PageCount == 0)
                    {
                        PageCount = 1;
                    }

                    //check link button to invisible or visible
                    if (CurPage == 1)
                    {
                        btnFirst.Visible = false;
                        btnPrevious.Visible = false;
                        btnLast.Visible = true;
                        btnNext.Visible = true;
                    }
                    if (CurPage == PageCount && PageCount == 1)
                    {
                        btnFirst.Visible = false;
                        btnPrevious.Visible = false;
                        btnLast.Visible = false;
                        btnNext.Visible = false;
                    }
                    else
                    {
                        if (CurPage == PageCount)
                        {
                            btnFirst.Visible = true;
                            btnPrevious.Visible = true;
                            btnLast.Visible = false;
                            btnNext.Visible = false;
                        }
                    }
                    if (CurPage > 1 && CurPage < PageCount)
                    {
                        btnFirst.Visible = true;
                        btnPrevious.Visible = true;
                        btnLast.Visible = true;
                        btnNext.Visible = true;
                    }
                    //show on grid view
                    GridViewTeam.DataSource = teams.Skip((CurPage - 1) * 10).Take(10);
                    GridViewTeam.DataBind();
                }
            }
        }

        /// <summary>
        /// handle event of page load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            hiddentFielId = new HiddenField();
            ButtonSave.Enabled = false;
            if (!IsPostBack)
            {
                hiddentFielId.Value = Request.Params["departmentId"];
                LoadData(Filter, SortType);
            }
        }

        /// <summary>
        /// handle event of ButtonDeactivate Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonDeactivate_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// handle event of ButtonSave Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonSave_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// handle event of ButtonBack Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ButtonBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("");
        }

        /// <summary>
        /// handle event of Button create Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CreateButton_Click(object sender, EventArgs e)
        {
            int department;
            if (Request.Params["departmentId"] != null)
            {
                if (int.TryParse(Request.Params["departmentId"], out department))
                {
                    Response.Redirect(string.Format(CultureInfo.CurrentCulture, "EditTeam.aspx?departmentid={0}", department));
                }
            }
        }

        /// <summary>
        /// handle event of checkbox inactive
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CheckBoxInactive_CheckedChanged(object sender, EventArgs e)
        {

            LoadData(Filter, SortType);
        }

        /// <summary>
        /// handle event of btnFirst Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnFirst_Click(object sender, EventArgs e)
        {
            CurPage = 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// handle event of btnNext Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnNext_Click(object sender, EventArgs e)
        {
            CurPage += 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// handle event of btnPrevious Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnPrevious_Click(object sender, EventArgs e)
        {
            CurPage -= 1;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// handle event of btnLast Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLast_Click(object sender, EventArgs e)
        {
            CurPage = PageCount;
            LoadData(Filter, SortType);
        }

        /// <summary>
        /// Handle the sorting action
        /// </summary>
        protected void GridViewTeam_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sort = e.SortExpression;
            //sort program name
            if (sort == "TeamName")
            {
                if (Flag[1] == 0)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 0;
                }
                SortType = "TeamName";
                LoadData(Filter, SortType);
            }
            //sort addressLine
            if (sort == "AddressLine")
            {
                if (Flag[1] == 1)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 1;
                }
                SortType = "AddressLine";
                LoadData(Filter, SortType);
            }
            //sort PostCode
            if (sort == "Postcode")
            {
                if (Flag[1] == 2)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 2;
                }
                SortType = "Postcode";
                LoadData(Filter, SortType);
            }


            //sort is KnownAs
            if (sort == "KnownAs")
            {
                if (Flag[1] == 3)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 3;
                }
                SortType = "KnownAs";
                LoadData(Filter, SortType);
            }


            //sort is active
            if (sort == "IsActive")
            {
                if (Flag[1] == 4)
                {
                    Flag[0]++;
                }
                else
                {
                    Flag[0] = 0;
                    Flag[1] = 4;
                }
                SortType = "IsActive";
                LoadData(Filter, SortType);
            }
        }

        /// <summary> 
        /// Handles the Command event of the LinkButtonOrganizationName control. 
        /// </summary> 
        /// <param name="sender">The source of the event.</param> 
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void LinkButtonPROName_Command(object sender, CommandEventArgs e)
        {
            TeamBus.SetStatusActive(Convert.ToInt32(e.CommandName));
            //Response.Redirect("ChangeStatus.aspx?TeamId=" + e.CommandName);
            Response.Redirect("EditTeam.aspx?TeamId=" + e.CommandName);
        }

        /// <summary>
        /// Handles the Command event of the GridViewTeam control. 
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e"></param>
        protected void GridViewTeam_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[0].HasControls())
                {
                    LinkButton LinkButtonPROName = ((LinkButton)e.Row.Cells[0].Controls[1]);
                    var teams = e.Row.DataItem as SD.DataAccess.Team;
                    if (teams.IsActive == false)
                        LinkButtonPROName.Attributes.Add("onclick",
                            "if(confirm(\"Do you want to make this team active?\") == true)"
                            + "{return true;} else {window.location.href='EditTeam.aspx?TeamId= " + teams.TeamId + "'; return false;}");
                    
                }
            }
        }

        /// <summary>
        /// Event handles the filter action
        /// </summary>
        protected void FilterByLetters_Command(object sender, CommandEventArgs e)
        {
            //sort type
            CurPage = 0;
            Filter = StringTools.GetLetterGroup(e.CommandName);
            LoadData(Filter, SortType);
        }
    }
}